<template>
  <div class="container">
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <el-form :inline="true" :model="boxQueryParam" class="demo-form-inline">
        <el-form-item label="选择读写器:">
          <el-select v-model="boxQueryParam.deviceId" placeholder="请选择读写器" clearable @change="changeReader"
            @clear="clearReader">
            <el-option v-for="(item, index) in readerOptions" :key="index" :label="item.label" :value="item.value"
              :disabled="item.disabled">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px; margin-left: 10px">{{
                item.type === '0' ? '超高频' : '高频'
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-tooltip :content="IsScanning ? '关闭读写器扫描' : '选择读写器开启扫描'" placement="top" effect="light">
            <el-button v-if="IsScanning" type="primary" @click="takeOff">关闭扫描</el-button>
            <el-button v-else type="primary" @click="enableScanning(activeName)">开启扫描</el-button>
          </el-tooltip>
          <el-button @click="empty(activeName)"><el-icon>
              <Delete />
            </el-icon>清空列表</el-button>
          <span v-if="IsScanning" style="font-size: 16px; margin-left: 10px; color: #409eff">
            <i class="el-icon-loading"></i>
            正在读取标签···</span>
        </el-form-item>
        <el-form-item style="float: right">
          <el-tooltip content="勾选未上架或已下架的档案/档案盒" placement="top" effect="light">
            <el-button type="primary" @click="handleUp(activeName)">上架</el-button>
          </el-tooltip>
          <el-tooltip content="勾选已上架的档案/档案盒" placement="top" effect="light">
            <el-button type="primary" @click="handleDown(activeName)">下架</el-button>
          </el-tooltip>
          <el-tooltip content="勾选已上架且在库的档案/档案盒" placement="top" effect="light">
            <el-button type="primary" @click="handleOut(activeName)">出库</el-button>
          </el-tooltip>
          <el-tooltip content="勾选离库的档案/档案盒" placement="top" effect="light">
            <el-button type="primary" @click="handleIn(activeName)">入库</el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </el-card>
    <el-tabs v-model="activeName" tab-position="left" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="档案盒" name="box">
        <el-table :data="boxTableData" row-key="rfid" border style="width: 100%" height="67vh" ref="boxtable"
          @selection-change="boxSelectionChange">
          <el-table-column type="selection" width="55" align="center" sortable> </el-table-column>
          <el-table-column type="index" label="序号" width="50" align="center" sortable>
          </el-table-column>
          <el-table-column v-for="item of boxTableProps" :key="item.props" :prop="item.prop" :label="item.title"
            :min-width="item.width" :show-overflow-tooltip="item.showOverflowTooltip">
            <template #default="scope">
              <span v-if="item.prop === 'stageStatus'">
                <el-tag v-show="scope.row.stageStatus == 0">未上架</el-tag>
                <el-tag v-show="scope.row.stageStatus == 1" type="success">已上架</el-tag>
                <el-tag v-show="scope.row.stageStatus == 2" type="danger">已下架</el-tag>
              </span>
              <span v-else-if="item.prop === 'storeStatus'">
                <el-tag :type="statusInfo(scope.row).type">
                  {{ statusInfo(scope.row).text }}
                </el-tag>
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="150">
            <template #default="{ row }">
              <el-button class="button10Left" v-if="row.labelId === null" link style="color: #67c23a"
                @click="handleRegister(row, 'box')">注册</el-button>
              <el-popconfirm class="button10Left" title="确定要删除吗？" @confirm="() => handleDel(row, 1)">
                <el-button slot="reference" icon="el-icon-delete" link class="danger_button">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="档案" name="archive">
        <el-table :data="archiveTableData" row-key="rfid" border style="width: 100%" height="67vh" ref="archivetable"
          @selection-change="archiveSelectionChange">
          <el-table-column type="selection" width="55" align="center" sortable> </el-table-column>
          <el-table-column type="index" label="序号" width="50" align="center" sortable>
          </el-table-column>
          <el-table-column v-for="item of archiveTableProps" :key="item.props" :prop="item.prop" :label="item.title"
            :width="item.width" :show-overflow-tooltip="item.showOverflowTooltip">
            <template #default="scope">
              <span v-if="item.prop === 'stageStatus'">
                <el-tag v-show="scope.row.stageStatus == 0">未上架</el-tag>
                <el-tag v-show="scope.row.stageStatus == 1" type="success">已上架</el-tag>
                <el-tag v-show="scope.row.stageStatus == 2" type="danger">已下架</el-tag>
              </span>
              <span v-else-if="item.prop === 'storeStatus'">
                <el-tag :type="statusInfo(scope.row).type">
                  {{ statusInfo(scope.row).text }}
                </el-tag>
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="150">
            <template #default="{ row }">
              <el-button class="button10Left" v-if="row.labelId === null" link style="color: #67c23a"
                @click="handleRegister(row, 'archive')">注册</el-button>
              <el-popconfirm class="button10Left" title="确定要删除吗？" @confirm="() => handleDel(row, 0)">
                <el-button slot="reference" icon="el-icon-delete" link class="danger_button">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <archives-out-dialog ref="archivesOutDialog" @ok="archivesInOrOutOk"></archives-out-dialog>
    <box-out-dialog ref="boxOutDialog" @ok="boxInOrOutOk"></box-out-dialog>
    <archives-in-dialog ref="archivesInDialog" @ok="archivesInOrOutOk"></archives-in-dialog>
    <box-in-dialog ref="boxInDialog" @ok="boxInOrOutOk"></box-in-dialog>
    <down-shelves-dialog ref="downShelvesDialog" @ok="upOrDownOk"></down-shelves-dialog>
    <up-shelves-dialog ref="upShelvesDialog" @ok="upOrDownOk"></up-shelves-dialog>
    <register-choose ref="registerChoose" @ok="registerOk"></register-choose>
  </div>
</template>

<script>
import archivesOutDialog from '@/views/rfid/dialog/archivesOutDialog.vue'
import boxOutDialog from '@/views/rfid/dialog/boxOutDialog.vue'
import archivesInDialog from '@/views/rfid/dialog/archivesInDialog.vue'
import boxInDialog from '@/views/rfid/dialog/boxInDialog.vue'
import downShelvesDialog from '@/views/rfid/dialog/downShelvesDialog.vue'
import upShelvesDialog from '@/views/rfid/dialog/upShelvesDialog.vue'
import registerChoose from '@/views/rfid/dialog/registerChoose.vue'
import { dropDown, getInfo } from '@/api/bas/rfidReader'
import { listByRfids } from '@/api/rfid/label'
import common from '@/utils/common'
import axios from 'axios'
import { ElNotification } from 'element-plus'
export default {
  name: 'AmsCar',
  components: {
    archivesOutDialog,
    boxOutDialog,
    archivesInDialog,
    boxInDialog,
    downShelvesDialog,
    upShelvesDialog,
    registerChoose,
  },
  data() {
    return {
      IsScanning: false,
      activeName: 'box',
      readerInfo: {},
      readerOptions: [],
      timeGetData: null,
      boxQueryParam: {
        deviceId: '',
        state: '未选择读写器',
        type: 'danger',
      },
      boxTableData: [],
      boxTableProps: [
        { title: '盒号', prop: 'boxNo', width: '', checked: true, showOverflowTooltip: true },
        { title: '盒名', prop: 'boxName', width: '', checked: true, showOverflowTooltip: true },
        { title: 'RFID', prop: 'rfid', width: '100', checked: true, showOverflowTooltip: true },
        {
          title: '位置',
          prop: 'positionName',
          width: '',
          checked: true,
          showOverflowTooltip: true,
        },
        {
          title: '上架状态',
          prop: 'stageStatus',
          width: '',
          checked: true,
          showOverflowTooltip: true,
        },
        {
          title: '在库状态',
          prop: 'storeStatus',
          width: '',
          checked: true,
          showOverflowTooltip: true,
        },
      ],
      boxSelectionData: [],
      archiveQueryParam: {
        labelType: 0,
      },
      archiveTableData: [],
      archiveTableProps: [
        { title: '档号', prop: 'archiveNo', width: '', checked: true, showOverflowTooltip: true },
        { title: '盒号', prop: 'boxNo', width: '', checked: true, showOverflowTooltip: true },
        { title: '题名', prop: 'archiveName', width: '', checked: true, showOverflowTooltip: true },
        { title: 'RFID', prop: 'rfid', width: '', checked: true, showOverflowTooltip: true },
        {
          title: '位置',
          prop: 'positionName',
          width: '',
          checked: true,
          showOverflowTooltip: true,
        },
        {
          title: '上架状态',
          prop: 'stageStatus',
          width: '',
          checked: true,
          showOverflowTooltip: true,
        },
        {
          title: '在库状态',
          prop: 'storeStatus',
          width: '',
          checked: true,
          showOverflowTooltip: true,
        },
      ],
      archiveSelectionData: [],
      boxScanning: false,
      archiveScanning: false,
    }
  },

  mounted() {
    this.getReader()
  },
  destroyed() {
    if (this.boxScanning || this.archiveScanning) {
      this.takeOff()
    }
  },
  methods: {
    statusInfo(row) {
      if (row.storeStatus === 0) return { type: '', text: '未入库' }
      if (row.storeStatus === 1) {
        return row.stageStatus === 1
          ? { type: 'success', text: '在库' }
          : { type: 'warning', text: '暂存' }
      }
      if (row.storeStatus === 2) return { type: 'danger', text: '离库' }
      return { type: '', text: '无' }
    },
    getReader() {
      dropDown()
        .then((res) => {
          if (res.data.code === 200) {
            this.readerOptions = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    changeReader(value) {
      if (value !== '' && value !== null) {
        getInfo(value)
          .then((res) => {
            if (res.data.code === 200) {
              this.readerInfo = res.data.data
              // this.takeOn(res.data.data.deviceIp, res.data.data.devicePort)
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err)
          })
      }
    },
    // 清空读写器
    clearReader() {
      this.readerInfo = {}
    },
    // 开启扫描
    enableScanning(type) {
      const that = this
      // 先选择读写器
      if (that.readerInfo.deviceIp === undefined) {
        this.$message.warning('请选择读写器')
      } else {
        const kongArr = []
        let url =
          'http://' + that.readerInfo.deviceIp + ':' + that.readerInfo.devicePort + '/takeon'
        axios
          .get(url, { timeout: 10000 })
          .then((res) => {
            if (res.data.search('ok') !== -1) {
              if (type === 'box') {
                that.boxScanning = true
              } else if (type === 'archive') {
                that.archiveScanning = true
              }
              ElNotification({
                message: '开启扫描成功',
                type: 'success',
              })
              that.timeGetData = setInterval(() => {
                common.getRifd(that.readerInfo.deviceIp, that.readerInfo.devicePort, that.readerInfo.deviceType).then((res) => {
                  for (let i = 0; i < res.length; i++) {
                    if (!kongArr.some((item) => item === res[i])) {
                      kongArr.push(res[i])
                    }
                  }
                  that.getData(kongArr, type)
                })
              }, 2000)
              this.IsScanning = true
            } else {
              ElNotification({
                message: '开启扫描失败',
                type: 'warning',
              })
            }
          })
          .catch((error) => {
            this.$message.warning('连接失败')
          })
      }
    },
    // 根据rfidd号查询档案
    getData(e, type) {
      const data = {
        labelType: type === 'archive' ? 0 : 1,
        rfidList: e,
      }
      listByRfids(data).then((res) => {
        this.$nextTick(() => {
          //1.将拿到的档案遍历
          let rfidList = res.data.data.map((x) => x.rfid)
          if (type === 'archive') {
            this.archiveTableData = res.data.data.map((obj) => {
              if (rfidList.includes(obj.rfid)) {
                return { ...obj }
              }
              return obj
            })
          } else if (type === 'box') {
            this.boxTableData = res.data.data.map((obj) => {
              if (rfidList.includes(obj.rfid)) {
                return { ...obj }
              }
              return obj
            })
          }
        })
      })
    },
    // 关闭扫描
    takeOff() {
      const that = this
      // 先选择读写器
      if (that.readerInfo.deviceIp === undefined) {
        this.$message.warning('请选择读写器并开启扫描')
      } else {
        let url =
          'http://' + that.readerInfo.deviceIp + ':' + that.readerInfo.devicePort + '/takeoff'
        axios
          .get(url, { timeout: 1000 })
          .then((res) => {
            if (res.data.search('ok') !== -1) {
              that.boxScanning = false
              that.archiveScanning = false
              this.IsScanning = false

              ElNotification({
                message: '关闭扫描成功',
                type: 'success',
              })
              clearInterval(this.timeGetData)
            }
          })
          .catch((error) => {
            this.$message.warning('连接失败')
          })
      }
    },
    // 清空
    empty(type) {
      if (this.readerInfo.deviceIp === undefined) {
        this.$message.warning('请选择读写器')
        return
      }
      if (this.IsScanning) {
        this.$message.warning('请先关闭读写器')
        return
      }
      if (type === 'archive') {
        this.archiveTableData = []
        this.archiveSelectionData = []
      } else if (type === 'box') {
        this.boxTableData = []
        this.boxSelectionData = []
      }
    },
    takeOn(ip, port) {
      const that = this
      let url = 'http://' + ip + ':' + port + '/takeon'
      axios
        .get(url, { timeout: 10000 })
        .then((res) => {
          if (res.data.search('ok') !== -1) {
            that.boxQueryParam.state = '正常'
            that.boxQueryParam.type = 'success'
          } else {
            that.boxQueryParam.state = '离线'
          }
        })
        .catch((error) => {
          that.boxQueryParam.state = '离线'
          this.$message.warning('连接失败')
        })
    },
    handleClick(tab, event) {
      if (tab.name === 'archive') {
        // this.archiveTableData = []
        // 若档案盒没有关闭扫描，先关闭
        if (this.boxScanning) {
          this.takeOff()
        }
      } else if (tab.name === 'box') {
        // this.boxTableData = []
        if (this.archiveScanning) {
          this.takeOff()
        }
      }
    },
    boxSelectionChange(val) {
      this.boxSelectionData = val
    },
    archiveSelectionChange(val) {
      this.archiveSelectionData = val
    },
    // 注册
    handleRegister(row, type) {
      this.$refs.registerChoose.init(row.rfid, type)
    },
    // 删除
    handleDel(row, type) {
      if (type === 0) {
        this.archiveTableData = this.archiveTableData.filter((item) => item.rfid !== row.rfid)
      } else if (type === 1) {
        this.boxTableData = this.boxTableData.filter((item) => item.rfid !== row.rfid)
      }
    },
    handleUp(type) {
      if (type === 'box') {
        if (this.boxSelectionData.length === 0) {
          this.$message.warning('请选择要上架的档案盒')
          return
        }
        // 已上架或销毁的不允许再次上架
        if (
          this.boxSelectionData.some((item) => item.stageStatus === 1 || item.stageStatus === 3)
        ) {
          this.$message.warning('存在不符合上架条件的档案盒')
          return
        }
        // 离库的档案盒不能上架
        if (this.boxSelectionData.some((item) => item.storeStatus === 2)) {
          this.$message.warning('存在离库的档案盒')
          return
        }
        // 未注册的档案盒不允许上架
        if (this.boxSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案盒')
          return
        }
        this.$refs.upShelvesDialog.add(this.boxSelectionData, 'box')
      } else if (type === 'archive') {
        if (this.archiveSelectionData.length === 0) {
          this.$message.warning('请选择要上架的档案')
          return
        }
        // 已上架或销毁的不允许再次上架
        if (
          this.archiveSelectionData.some((item) => item.stageStatus === 1 || item.stageStatus === 3)
        ) {
          this.$message.warning('存在不符合上架条件的档案')
          return
        }
        // 离库的档案不能上架
        if (this.archiveSelectionData.some((item) => item.storeStatus === 2)) {
          this.$message.warning('存在离库的档案')
          return
        }
        // 已装盒的档案不允许单独上架
        if (this.archiveSelectionData.some((item) => item.boxNo !== null)) {
          this.$message.warning('已装盒的档案不允许上架')
          return
        }
        // 未注册的档案不允许上架
        if (this.archiveSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案')
          return
        }
        this.$refs.upShelvesDialog.add(this.archiveSelectionData, 'archive')
      }
    },
    handleDown(type) {
      if (type === 'box') {
        if (this.boxSelectionData.length === 0) {
          this.$message.warning('请选择要下架的档案盒')
          return
        }
        // 已上架或销毁的不允许再次下架
        if (this.boxSelectionData.some((item) => item.stageStatus === 2)) {
          this.$message.warning('存在不符合下架条件的档案盒')
          return
        }
        // 未注册的档案盒不允许下架
        if (this.boxSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案盒')
          return
        }
        this.$refs.downShelvesDialog.add(this.boxSelectionData, 'box')
      } else if (type === 'archive') {
        if (this.archiveSelectionData.length === 0) {
          this.$message.warning('请选择要下架的档案')
          return
        }
        // 已装盒的档案不允许单独下架
        if (this.archiveSelectionData.some((item) => item.boxNo !== null)) {
          this.$message.warning('已装盒的档案不允许下架')
          return
        }
        // 已上架或销毁的不允许再次下架
        if (this.archiveSelectionData.some((item) => item.stageStatus === 2)) {
          this.$message.warning('存在不符合下架条件的档案')
          return
        }
        // 未注册的档案不允许下架
        if (this.archiveSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案')
          return
        }
        this.$refs.downShelvesDialog.add(this.archiveSelectionData, 'archive')
      }
    },
    handleOut(type) {
      if (type === 'box') {
        if (this.boxSelectionData.length === 0) {
          this.$message.warning('请选择要出库的档案盒')
          return
        }
        // 在库且已上架或已下架的档案盒可以出库
        if (
          this.boxSelectionData.some((item) => (item.stageStatus !== 1 && item.stageStatus !== 2) || item.storeStatus !== 1)
        ) {
          this.$message.warning('存在不符合出库条件的档案盒')
          return
        }
        // 已下架和已上架的不能同时出库
        if (
          this.boxSelectionData.some((item) => item.stageStatus === 2) &&
          this.boxSelectionData.some((item) => item.stageStatus === 1)
        ) {
          this.$message.warning('已下架和已上架的不能同时出库')
          return
        }
        // 未注册的档案盒不允许出库
        if (this.boxSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案盒')
          return
        }
        this.$refs.boxOutDialog.add(this.boxSelectionData)
      } else if (type === 'archive') {
        if (this.archiveSelectionData.length === 0) {
          this.$message.warning('请选择要出库的档案')
          return
        }
        // 在库且已上架或已下架的可以出库
        if (
          this.archiveSelectionData.some((item) => (item.stageStatus !== 1 && item.stageStatus !== 2) || item.storeStatus !== 1)
        ) {
          this.$message.warning('存在不符合出库条件的档案')
          return
        }
        // 已下架和已上架的不能同时出库
        if (
          this.archiveSelectionData.some((item) => item.stageStatus === 2) &&
          this.archiveSelectionData.some((item) => item.stageStatus === 1)
        ) {
          this.$message.warning('已下架和已上架的不能同时出库')
          return
        }
        // 未注册的档案不允许出库
        if (this.archiveSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案')
          return
        }
        this.$refs.archivesOutDialog.add(this.archiveSelectionData)
      }
    },
    handleIn(type) {
      if (type === 'box') {
        if (this.boxSelectionData.length === 0) {
          this.$message.warning('请选择要入库的档案盒')
          return
        }
        // 离库的可以入库
        if (this.boxSelectionData.some((item) => item.storeStatus !== 2)) {
          this.$message.warning('存在不符合入库条件的档案盒')
          return
        }
        // 未注册的档案盒不允许入库
        if (this.boxSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案盒')
          return
        }
        this.$refs.boxInDialog.add(this.boxSelectionData)
      } else if (type === 'archive') {
        if (this.archiveSelectionData.length === 0) {
          this.$message.warning('请选择要入库的档案')
          return
        }
        // 已装盒的档案不允许单独入库
        if (this.archiveSelectionData.some((item) => item.boxNo !== null)) {
          this.$message.warning('已装盒的档案不允许入库')
          return
        }
        // 已上架或销毁的不允许再次入库
        if (this.archiveSelectionData.some((item) => item.storeStatus !== 2)) {
          this.$message.warning('存在不符合入库条件的档案')
          return
        }
        // 未注册的档案不允许入库
        if (this.archiveSelectionData.some((item) => item.labelId === null)) {
          this.$message.warning('存在未注册的档案')
          return
        }
        this.$refs.archivesInDialog.add(this.archiveSelectionData)
      }
    },
    archivesInOrOutOk(data) {
      this.archiveTableData = this.archiveTableData.filter((item) => {
        if (data.some((item2) => item2.rfid === item.rfid)) {
          return false
        } else {
          return true
        }
      })
    },
    boxInOrOutOk(data) {
      this.boxTableData = this.boxTableData.filter((item) => {
        if (data.some((item2) => item2.rfid === item.rfid)) {
          return false
        } else {
          return true
        }
      })
    },
    upOrDownOk(type, data) {
      if (type === 'archive') {
        this.archiveTableData = this.archiveTableData.filter((item) => {
          if (data.some((item2) => item2.rfid === item.rfid)) {
            return false
          } else {
            return true
          }
        })
      } else if (type === 'box') {
        this.boxTableData = this.boxTableData.filter((item) => {
          if (data.some((item2) => item2.rfid === item.rfid)) {
            return false
          } else {
            return true
          }
        })
      }
    },
    registerOk(rfid, type) {
      this.archiveTableData = this.archiveTableData.filter((item) => item.rfid !== rfid)
      this.boxTableData = this.boxTableData.filter((item) => item.rfid !== rfid)
    },
  },
}
</script>

<style lang="less" scoped>
@import '../../style/tabs.less';


.demo-form-inline {
  .el-form-item {
    margin-bottom: 0;
  }

  :deep(.el-select) {
    width: 220px;
  }
}

.el-tabs__item {
  height: 50%;
}
</style>
